<template>
  <div class="dashboard-container" v-loading="loading" element-loading-text="加载中...">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1 class="welcome-title">欢迎回来！</h1>
        <p class="welcome-subtitle">企业智能组织管理系统</p>
        <div class="welcome-time">{{ currentTime }}</div>
      </div>
      <div class="welcome-illustration">
        <div class="floating-card card-1"></div>
        <div class="floating-card card-2"></div>
        <div class="floating-card card-3"></div>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card total-employees">
            <div class="stat-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ totalEmployees }}</div>
              <div class="stat-label">总员工数</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card total-students">
            <div class="stat-icon">
              <i class="el-icon-s-custom"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ totalStudents }}</div>
              <div class="stat-label">总学生数</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card active-students">
            <div class="stat-icon">
              <i class="el-icon-success"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ studentStats.activeStudents || 0 }}</div>
              <div class="stat-label">在读学生</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="stat-card total-depts">
            <div class="stat-icon">
              <i class="el-icon-office-building"></i>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ deptCount || 0 }}</div>
              <div class="stat-label">部门数量</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 员工性别分布 -->
        <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
          <div class="chart-card" v-loading="chartsLoading">
            <div class="chart-header">
              <h3>员工性别分布</h3>
              <el-button type="text"
                size="mini"
                @click="initEmpGenderChart"
                title="刷新图表"
              >
                <i class="el-icon-refresh"></i>
              </el-button>
            </div>
            <div class="chart-content">
              <div ref="empGenderChart" class="chart"></div>
            </div>
          </div>
        </el-col>

        <!-- 学生状态分布 -->
        <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
          <div class="chart-card" v-loading="chartsLoading">
            <div class="chart-header">
              <h3>学生状态分布</h3>
              <el-button
                type="text"
                size="mini"
                @click="initStudentStatusChart"
                title="刷新图表"
              >
                <i class="el-icon-refresh"></i>
              </el-button>
            </div>
            <div class="chart-content">
              <div ref="studentStatusChart" class="chart"></div>
            </div>
          </div>
        </el-col>

        <!-- 入学年份趋势 -->
        <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
          <div class="chart-card" v-loading="chartsLoading">
            <div class="chart-header">
              <h3>入学年份趋势</h3>
              <el-button
                type="text"
                size="mini"
                @click="initYearTrendChart"
                title="刷新图表"
              >
                <i class="el-icon-refresh"></i>
              </el-button>
            </div>
            <div class="chart-content">
              <div ref="yearTrendChart" class="chart"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 快捷操作区域 -->
    <div class="quick-actions">
      <div class="section-title">快捷操作</div>
      <el-row :gutter="15">
        <el-col :xs="12" :sm="8" :md="6" :lg="4" :xl="4">
          <div class="action-card" @click="$router.push('/system/emp')">
            <div class="action-icon emp-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="action-text">员工管理</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="4" :xl="4">
          <div class="action-card" @click="$router.push('/example/student')">
            <div class="action-icon student-icon">
              <i class="el-icon-s-custom"></i>
            </div>
            <div class="action-text">学生管理</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="4" :xl="4">
          <div class="action-card" @click="$router.push('/system/dept')">
            <div class="action-icon dept-icon">
              <i class="el-icon-office-building"></i>
            </div>
            <div class="action-text">部门管理</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="4" :xl="4">
          <div class="action-card" @click="$router.push('/example/classes')">
            <div class="action-icon class-icon">
              <i class="el-icon-school"></i>
            </div>
            <div class="action-text">班级管理</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="4" :xl="4">
          <div class="action-card" @click="$router.push('/message/messageList')">
            <div class="action-icon message-icon">
              <i class="el-icon-bell"></i>
            </div>
            <div class="action-text">公告管理</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="8" :md="6" :lg="4" :xl="4">
          <div class="action-card" @click="$router.push('/log/log')">
            <div class="action-icon log-icon">
              <i class="el-icon-document"></i>
            </div>
            <div class="action-text">操作日志</div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getEmpStats } from "@/api/emp";
import { getStudentStats } from "@/api/student";
import { findAll as getDepts } from "@/api/dept";
import * as echarts from "echarts";

export default {
  name: "Dashboard",
  data() {
    return {
      empCount: 0,
      stuCount: 0,
      classCount: 0,
      deptCount: 0,
      currentTime: "",
      empStats: {},
      studentStats: {},
      deptCount: 0,
      empGenderChart: null,
      studentStatusChart: null,
      yearTrendChart: null,
      loading: false,
      chartsLoading: false,
      resizeObserver: null,
      themeObserver: null,
    };
  },
  computed: {
    // 缓存计算总员工数
    totalEmployees() {
      if (!this.empStats.genderCounts) return 0;
      return (this.empStats.genderCounts['1'] || 0) + (this.empStats.genderCounts['2'] || 0);
    },
    // 缓存计算总学生数
    totalStudents() {
      return (this.studentStats.activeStudents || 0) + (this.studentStats.inactiveStudents || 0);
    },
    // 缓存处理员工性别数据
    processedEmpGenderData() {
      if (!this.empStats.genderCounts) return [];
      const genderData = this.empStats.genderCounts;
      return [
        { value: genderData["1"] || 0, name: "男性" },
        { value: genderData["2"] || 0, name: "女性" },
      ];
    },
    // 缓存处理学生状态数据
    processedStudentStatusData() {
      return [
        { value: this.studentStats.activeStudents || 0, name: "在读" },
        { value: this.studentStats.inactiveStudents || 0, name: "已离开" },
      ];
    },
    // 缓存处理年份趋势数据
    processedYearTrendData() {
      if (!this.studentStats.yearCounts) return { years: [], values: [] };
      const yearData = this.studentStats.yearCounts;
      const years = Object.keys(yearData).sort();
      const values = years.map((year) => yearData[year]);
      return { years, values };
    },
    // 缓存图表实例数组
    chartInstances() {
      return [this.empGenderChart, this.studentStatusChart, this.yearTrendChart].filter(Boolean);
    }
  },
  mounted() {
    this.updateTime();
    this.timeInterval = setInterval(this.updateTime, 1000);
    this.loadData();
    this.initResizeObserver();
    this.initThemeObserver();
  },
  beforeDestroy() {
    // 清理定时器
    if (this.timeInterval) {
      clearInterval(this.timeInterval);
      this.timeInterval = null;
    }

    // 清理图表实例
    this.chartInstances.forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
    this.empGenderChart = null;
    this.studentStatusChart = null;
    this.yearTrendChart = null;

    // 清理观察器
    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = null;
    }
    if (this.themeObserver) {
      this.themeObserver.disconnect();
      this.themeObserver = null;
    }
  },
  methods: {
    updateTime() {
      const now = new Date();
      const options = {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        weekday: "long",
      };
      this.currentTime = now.toLocaleDateString("zh-CN", options);
    },

    // 防抖工具函数
    debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    },

    // 优化的数据加载方法
    async loadData() {
      this.loading = true;
      this.chartsLoading = true;

      try {
        console.log("开始加载数据...");

        // 并行加载所有数据
        const [empResponse, studentResponse, deptResponse] = await Promise.all([
          getEmpStats(),
          getStudentStats(),
          getDepts()
        ]);

        // 处理员工统计数据
        if (empResponse && empResponse.data.code === 1 && empResponse.data.data) {
          this.empStats = empResponse.data.data;
          console.log("员工统计数据设置成功:", this.empStats);
        } else {
          console.error("员工统计数据格式错误:", empResponse);
        }

        // 处理学生统计数据
        if (studentResponse && studentResponse.data.code === 1 && studentResponse.data.data) {
          this.studentStats = studentResponse.data.data;
          console.log("学生统计数据设置成功:", this.studentStats);
        } else {
          console.error("学生统计数据格式错误:", studentResponse);
        }

        // 处理部门数据
        if (deptResponse && deptResponse.data.code === 1 && deptResponse.data.data) {
          this.deptCount = deptResponse.data.data.length;
          console.log("部门数量设置成功:", this.deptCount);
        } else {
          console.error("部门数据格式错误:", deptResponse);
        }

        // 延迟初始化图表以确保DOM已更新
        this.$nextTick(() => {
          this.initAllCharts();
          this.chartsLoading = false;
        });

      } catch (error) {
        console.error("加载数据失败:", error);
        this.$message.error("加载数据失败: " + error.message);
        this.chartsLoading = false;
      } finally {
        this.loading = false;
      }
    },

    // 批量初始化所有图表
    initAllCharts() {
      this.initEmpGenderChart();
      this.initStudentStatusChart();
      this.initYearTrendChart();
    },

    // 优化的员工性别图表初始化
    initEmpGenderChart() {
      if (this.processedEmpGenderData.length === 0) {
        console.log("员工性别统计数据为空");
        return;
      }

      if (this.empGenderChart) {
        this.empGenderChart.dispose();
      }

      this.empGenderChart = echarts.init(this.$refs.empGenderChart);
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          bottom: "5%",
          left: "center",
        },
        series: [
          {
            name: "员工性别",
            type: "pie",
            radius: ["40%", "70%"],
            center: ["50%", "45%"],
            data: this.processedEmpGenderData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      this.empGenderChart.setOption(option);
    },

    // 优化的学生状态图表初始化
    initStudentStatusChart() {
      if (this.processedStudentStatusData.every(item => item.value === 0)) {
        console.log("学生状态统计数据为空");
        return;
      }

      if (this.studentStatusChart) {
        this.studentStatusChart.dispose();
      }

      this.studentStatusChart = echarts.init(this.$refs.studentStatusChart);
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          bottom: "5%",
          left: "center",
        },
        series: [
          {
            name: "学生状态",
            type: "pie",
            radius: ["40%", "70%"],
            center: ["50%", "45%"],
            data: this.processedStudentStatusData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      this.studentStatusChart.setOption(option);
    },

    // 优化的年份趋势图表初始化
    initYearTrendChart() {
      const { years, values } = this.processedYearTrendData;
      if (years.length === 0) {
        console.log("学生入学年份统计数据为空");
        return;
      }

      if (this.yearTrendChart) {
        this.yearTrendChart.dispose();
      }

      this.yearTrendChart = echarts.init(this.$refs.yearTrendChart);
      const option = {
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: years,
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "入学人数",
            type: "line",
            data: values,
            smooth: true,
            itemStyle: {
              color: "#5470c6",
            },
            areaStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: "rgba(84, 112, 198, 0.3)" },
                  { offset: 1, color: "rgba(84, 112, 198, 0.1)" },
                ],
              },
            },
          },
        ],
      };
      this.yearTrendChart.setOption(option);
    },

    // 批量处理图表resize
    handleResize() {
      this.chartInstances.forEach(chart => {
        try {
          if (chart) {
            chart.resize();
          }
        } catch (error) {
          console.error('图表resize失败:', error);
        }
      });
    },

    // 初始化resize观察器
    initResizeObserver() {
      const debouncedResize = this.debounce(this.handleResize, 100);

      if (window.ResizeObserver) {
        this.resizeObserver = new ResizeObserver(debouncedResize);
        this.resizeObserver.observe(this.$el);
      } else {
        // 降级到window resize事件
        window.addEventListener('resize', debouncedResize);
        this._windowResizeHandler = debouncedResize;
      }
    },

    // 初始化主题观察器
    initThemeObserver() {
      const debouncedThemeChange = this.debounce(() => {
        this.initAllCharts();
      }, 100);

      if (window.MutationObserver) {
        this.themeObserver = new MutationObserver(debouncedThemeChange);
        this.themeObserver.observe(document.documentElement, {
          attributes: true,
          attributeFilter: ['class']
        });
      }
    },

    // 刷新数据
    async refreshData() {
      await this.loadData();
    }
  },
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 50px);
  transform: translateZ(0);
  will-change: auto;
}

// 欢迎区域
.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 40px;
  margin-bottom: 30px;
  color: white;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .welcome-content {
    flex: 1;

    .welcome-title {
      font-size: 36px;
      font-weight: 700;
      margin: 0 0 10px 0;
      background: linear-gradient(45deg, #fff, #f0f8ff);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }

    .welcome-subtitle {
      font-size: 18px;
      opacity: 0.9;
      margin: 0 0 20px 0;
    }

    .welcome-time {
      font-size: 16px;
      opacity: 0.8;
      background: rgba(255, 255, 255, 0.1);
      padding: 8px 16px;
      border-radius: 20px;
      display: inline-block;
      backdrop-filter: blur(10px);
    }
  }

  .welcome-illustration {
    position: relative;
    width: 200px;
    height: 150px;

    .floating-card {
      position: absolute;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 12px;
      backdrop-filter: blur(10px);
      animation: float 6s ease-in-out infinite;

      &.card-1 {
        width: 80px;
        height: 60px;
        top: 20px;
        left: 20px;
        animation-delay: 0s;
      }

      &.card-2 {
        width: 60px;
        height: 80px;
        top: 40px;
        right: 30px;
        animation-delay: 2s;
      }

      &.card-3 {
        width: 70px;
        height: 50px;
        bottom: 30px;
        left: 50px;
        animation-delay: 4s;
      }
    }
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-10px) rotate(5deg);
  }
}

// 统计卡片区域
.stats-section {
  margin-bottom: 30px;

  .stat-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    display: flex;
    align-items: center;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    height: 120px;
    transform: translateZ(0);
    will-change: auto;

    &:hover {
      transform: translateY(-5px) translateZ(0);
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    }

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;
      margin-right: 20px;
    }

    .stat-content {
      flex: 1;

      .stat-number {
        font-size: 28px;
        font-weight: 700;
        color: #2d3748;
        margin-bottom: 4px;
      }

      .stat-label {
        font-size: 14px;
        color: #718096;
      }
    }

    &.total-employees .stat-icon {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.total-students .stat-icon {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }

    &.active-students .stat-icon {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    &.total-depts .stat-icon {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
  }
}

// 图表区域
.charts-section {
  margin-bottom: 30px;

  .chart-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    height: 350px;
    display: flex;
    flex-direction: column;
    transform: translateZ(0);
    will-change: auto;

    .chart-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: #2d3748;
      }

      .el-button {
        padding: 4px 8px;
        color: #409eff;

        &:hover {
          color: #66b1ff;
          background-color: #ecf5ff;
        }

        i {
          font-size: 14px;
        }
      }
    }

    .chart-content {
      flex: 1;
      transform: translateZ(0);
      will-change: auto;

      .chart {
        width: 100%;
        height: 100%;
        transform: translateZ(0);
        will-change: auto;
      }
    }
  }
}

// 快捷操作区域
.quick-actions {
  .section-title {
    font-size: 20px;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 20px;
  }

  .action-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    transform: translateZ(0);
    will-change: auto;

    &:hover {
      transform: translateY(-5px) translateZ(0);
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    }

    .action-icon {
      width: 50px;
      height: 50px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      color: white;
      margin-bottom: 12px;

      &.emp-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.student-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.dept-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }

      &.class-icon {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
      }

      &.message-icon {
        background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
      }

      &.log-icon {
        background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
      }
    }

    .action-text {
      font-size: 14px;
      font-weight: 500;
      color: #2d3748;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .dashboard-container {
    padding: 15px;
  }

  .welcome-section {
    padding: 30px 20px;
    flex-direction: column;
    text-align: center;

    .welcome-content {
      margin-bottom: 20px;

      .welcome-title {
        font-size: 28px;
      }
    }

    .welcome-illustration {
      width: 150px;
      height: 100px;
    }
  }

  .stats-section .stat-card {
    padding: 20px 15px;
    height: 100px;

    .stat-icon {
      width: 50px;
      height: 50px;
      font-size: 20px;
      margin-right: 15px;
    }

    .stat-content .stat-number {
      font-size: 24px;
    }
  }

  .charts-section .chart-card {
    height: 300px;
    margin-bottom: 20px;
  }

  .quick-actions .action-card {
    height: 100px;
    padding: 15px;

    .action-icon {
      width: 40px;
      height: 40px;
      font-size: 18px;
      margin-bottom: 8px;
    }

    .action-text {
      font-size: 12px;
    }
  }
}
</style>
